package yagwl.client.model;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import yagwl.client.model.MasterDetailEvent.EventType;
import yagwl.client.model.fnd.RpcStatus;

/**
 * Abstract class to manage cache of list of object on the client (browser)
 */
public abstract class MasterDetailListCache {

  private static Logger log = Logger.getLogger(MasterDetailListCache.class
      .getName());
  private boolean loadInProgress = false;
  private List<MasterDetailDTO> list = new ArrayList<MasterDetailDTO>();

  public List<MasterDetailDTO> getList() {
    return list;
  }

  public abstract void fetch();

  protected boolean isLoadInProgress() {
    return loadInProgress;
  }

  protected void loadStart() {
    loadInProgress = true;
    log.info("loadStart: Loading " + this.getClass().getName());
  }

  protected void onLoadSuccess(List<MasterDetailDTO> result) {
    log.info("onLoadSuccess: Entering");
    loadInProgress = false;
    list.addAll(result);
    throwDataReadyEvent(EventType.LoadSuccess);
  }

  protected void onLoadFailure(Throwable caught) {
    loadInProgress = false;
    log.info(caught.toString());
  }

  public void createMasterItem(MasterDetailDTO entity) {
    masterItemCreate(entity);
  }

  protected void masterItemCreated(MasterDetailDTO entity, RpcStatus result) {
    list.add(entity);
    throwDataReadyEvent(EventType.MasterItemCreated);
  }

  protected abstract void masterItemCreate(MasterDetailDTO mdDTO);

  public void updateMasterDetail(MasterDetailDTO mdDTO) {
    
  }

  public void deleteMasterDetail(int objIdx) {
    
  }
  
  public void createDetailItem(MasterDetailDTO mdDTO, ItemDTO detailDTO) {
    
  }

  public void deleteDetailItem(MasterDetailDTO mdDTO, ItemDTO detailDTO) {
    
  }

  /**
   * Throws ItemListEvent. Called when an asynchronous RPI for data manipulation
   * completes.
   */
  private void throwDataReadyEvent(EventType eventType) {
    DataReadyEventBus.getInstance().fireEvent(
        new MasterDetailEvent(this.getClass().getName(), eventType));
    log.info("throwDataReadyEvent: MasterDetailEvent raised: "
        + this.getClass().getName());
  }

  private void print() {
    log.info("print: " + this.getClass().getName());
    for (MasterDetailDTO item : list) {
      log.info(item.getId() + ":" + item.getLabel());
    }
  }

}
